package com.dgut.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dgut.dto.ListFormDto;
import com.dgut.dto.StatisticAO;
import com.dgut.dto.UserInfoAndDailyForm;
import com.dgut.mapper.AccountMapper;
import com.dgut.mapper.DailyFormMapper;
import com.dgut.mapper.UserInfoMapper;
import com.dgut.pojo.Account;
import com.dgut.pojo.DailyForm;
import com.dgut.pojo.UserInfo;
import com.dgut.service.DailyFormService;
import com.dgut.utils.MyDateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;


@Service
public class DailyFormServiceImpl extends ServiceImpl<DailyFormMapper, DailyForm> implements DailyFormService {
    @Resource
    AccountMapper accountMapper;
    @Resource
    DailyFormMapper dailyFormMapper;
    @Resource
    UserInfoMapper userInfoMapper;

    //获取某天的表单
    public DailyForm getFormByDate(String username,String date){
        Account account = accountMapper.getAccountByUsername(username);
        QueryWrapper<DailyForm> dailyFormQueryWrapper = new QueryWrapper<>();
        dailyFormQueryWrapper.eq("account_id",account.getAccountId());
        dailyFormQueryWrapper.apply("date_format(create_time,'%Y-%m-%d')='"+date+"'");
        DailyForm dailyForm= dailyFormMapper.selectOne(dailyFormQueryWrapper);
       return dailyForm;
    }

    //查询最新一天的数据,并返回填报的天数
    @Override
    public UserInfoAndDailyForm getLatestFormWithUserInfo(String username) {
        UserInfo userInfo = null;
        DailyForm dailyForm = null;
        Account account = accountMapper.getAccountByUsername(username);
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        QueryWrapper<DailyForm> dailyFormQueryWrapper = new QueryWrapper<>();

        //查询用户的数据
        userInfoQueryWrapper.eq("account_id",account.getAccountId());
        userInfo= userInfoMapper.selectOne(userInfoQueryWrapper);

        //查询dailyform中最新的数据
        dailyFormQueryWrapper.eq("account_id",account.getAccountId()).orderByDesc("create_time");
        List<DailyForm> dailyForms = dailyFormMapper.selectList(dailyFormQueryWrapper);
        if(!dailyForms.isEmpty()){
            dailyForm = dailyForms.get(0);  //获取第一个
        }
        return new UserInfoAndDailyForm(userInfo,dailyForm);
    }

    //填报当天的信息
    @Transactional
    @Override
    public int chockIn(String username, UserInfo userInfo,DailyForm dailyForm) throws Exception{
        Account account = accountMapper.getAccountByUsername(username);
        userInfo.setAccountId(account.getAccountId());
        userInfo.setCreateTime(null);
        userInfo.setUpdateTime(null);
        dailyForm.setAccountId(account.getAccountId());
        dailyForm.setCreateTime(null);
        dailyForm.setUpdateTime(null);
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("account_id",account.getAccountId());
        int fillingDays = 1;

        //更新userInfo
        userInfoMapper.update(userInfo, userInfoQueryWrapper);

        //查找昨天是否有填报信息表
        String date = MyDateUtil.getNthSimpleDate(-1);  //获取一天前的日期
        DailyForm formByDate = getFormByDate(username,date);
        if(formByDate==null){ //昨天没有填报
            dailyForm.setFillingDays(1);
        }else{
            fillingDays=formByDate.getFillingDays()+1;
            dailyForm.setFillingDays(fillingDays);
        }
        dailyFormMapper.insert(dailyForm);
        return fillingDays;
    }
    //获取大数据报表
    @Override
    public Map<String,List<StatisticAO>> getStatisticForm() {
        Map<String,List<StatisticAO>> result = new HashMap<String,List<StatisticAO>>();
        //查询当前日期的前7天数据
        String day = MyDateUtil.getNthSimpleDate(0);
        String day1 = MyDateUtil.getNthSimpleDate(-1);
        String day2 = MyDateUtil.getNthSimpleDate(-2);
        String day3 = MyDateUtil.getNthSimpleDate(-3);
        String day4 = MyDateUtil.getNthSimpleDate(-4);
        String day5 = MyDateUtil.getNthSimpleDate(-5);
        String day6 = MyDateUtil.getNthSimpleDate(-6);
        List<String> strings = Arrays.asList(day, day1, day2, day3, day4, day5,day6);
        String dayList = "('"+day+"','"+day1+"','"+day2+"','"+day3+"','"+day4+"','"+day5+"','"+day5+"')";
        //1、填报总人数
        QueryWrapper<DailyForm> wrapper1 = new QueryWrapper<>();
        wrapper1.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper1.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS1 = dailyFormMapper.getFormCount(wrapper1);
        this.insertZeroCount(strings, statisticAOS1);
        result.put("填报总人数",statisticAOS1);
        //2、身体状况良好的人数
        QueryWrapper<DailyForm> wrapper2 = new QueryWrapper<>();
        wrapper2.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper2.eq("physical_condition","良好");
        wrapper2.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS2 = dailyFormMapper.getFormCount(wrapper2);
        this.insertZeroCount(strings,statisticAOS2);
        result.put("身体状况良好人数",statisticAOS2);
        //3、近14天到达或途径疫情防控重点地区的人数
        QueryWrapper<DailyForm> wrapper3 = new QueryWrapper<>();
        wrapper3.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper3.eq("to_epidemic_area","是");
        wrapper3.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS3 = dailyFormMapper.getFormCount(wrapper3);
        this.insertZeroCount(strings,statisticAOS3);
        result.put("近14天到达或途径疫情防控重点地区的人数",statisticAOS3);
        //4、接触过“近14天出入过疫情重点防控地区”的人员的人数
        QueryWrapper<DailyForm> wrapper4 = new QueryWrapper<>();
        wrapper4.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper4.eq("contact_person","是");
        wrapper4.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS4 = dailyFormMapper.getFormCount(wrapper4);
        this.insertZeroCount(strings,statisticAOS4);
        result.put("接触过“近14天出入过疫情重点防控地区”的人员的人数",statisticAOS4);
        //5、接触过疑似/确诊病例的人数
        QueryWrapper<DailyForm> wrapper5 = new QueryWrapper<>();
        wrapper5.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper5.eq("contact_suspected_case","是");
        wrapper5.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS5 = dailyFormMapper.getFormCount(wrapper5);
        this.insertZeroCount(strings,statisticAOS5);
        result.put("近14天接触过疑似/确诊病例的人数",statisticAOS5);
        //6、在莞医学隔离观察人数
        QueryWrapper<DailyForm> wrapper6 = new QueryWrapper<>();
        wrapper6.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper6.like("is_medical_observation","是");
        wrapper6.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS6 = dailyFormMapper.getFormCount(wrapper6);
        this.insertZeroCount(strings,statisticAOS6);
        result.put("在莞医学隔离观察人数",statisticAOS6);
        //7、目前在莞人数
        QueryWrapper<DailyForm> wrapper7 = new QueryWrapper<>();
        wrapper7.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper7.like("in_guan","是");
        wrapper7.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS7 = dailyFormMapper.getFormCount(wrapper7);
        this.insertZeroCount(strings,statisticAOS7);
        result.put("目前在莞人数",statisticAOS7);
        //8、有离莞出行行动的人数
        QueryWrapper<DailyForm> wrapper8 = new QueryWrapper<>();
        wrapper8.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper8.like("is_leave_guan","是");
        wrapper8.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS8 = dailyFormMapper.getFormCount(wrapper8);
        this.insertZeroCount(strings,statisticAOS8);
        result.put("有离莞出行行动的人数",statisticAOS8);
        //9、重点人群人数
        QueryWrapper<DailyForm> wrapper9 = new QueryWrapper<>();
        wrapper9.apply("date_format(create_time,'%Y-%m-%d') in"+dayList);
        wrapper9.like("is_midpoint","是");
        wrapper9.groupBy("DATE(create_time)");
        List<StatisticAO> statisticAOS9 = dailyFormMapper.getFormCount(wrapper9);
        this.insertZeroCount(strings,statisticAOS9);
        result.put("重点人群人数",statisticAOS9);
        return result;
    }
    //填充数量为0的日期
    private List<StatisticAO> insertZeroCount(List<String> strings, List<StatisticAO> statisticAOS){
        for (String string : strings) {
            boolean contains = false;
            for (StatisticAO statisticAO : statisticAOS) {
                if(statisticAO.getDate().equals(string)){
                    contains = true;
                    break;
                }
            }
            if(!contains){
                StatisticAO ao = new StatisticAO(string,0);
                statisticAOS.add(ao);
            }
        }
        return statisticAOS;
    }

    //查询填报情况
    @Override
    public Page<Map<String,Object>> getFormList(Page<Map<String, Object>> page, ListFormDto listFormDto) {
        String date;
        String datePattern;
        String dateBefore;
        QueryWrapper<DailyForm> wrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(listFormDto.getName())){
            wrapper.like("name",listFormDto.getName());
        }
        if(StringUtils.isNotEmpty(listFormDto.getGender())){
            wrapper.eq("gender",listFormDto.getGender());
        }
        if(StringUtils.isNotEmpty(listFormDto.getDepartment())){
            wrapper.like("department",listFormDto.getDepartment());
        }
        if(StringUtils.isNotEmpty(listFormDto.getClassname())){
            wrapper.like("classname",listFormDto.getClassname());
        }
        if(listFormDto.getCreateTime()!=null){
            date = MyDateUtil.getNthSimpleDate(listFormDto.getCreateTime(),0);
            datePattern=MyDateUtil.getDateFromPattern(listFormDto.getCreateTime(),"MM月dd日");
            dateBefore = MyDateUtil.getDateFromPattern(listFormDto.getCreateTime(),-14,"yyyy年MM月dd日");
        }
        else{
            date = MyDateUtil.getNthSimpleDate(0);
            datePattern=MyDateUtil.getDateFromPattern(new Date(),"MM月dd日");
            dateBefore = MyDateUtil.getDateFromPattern(new Date(),-14,"yyyy年MM月dd日");
        }
        wrapper.apply("date_format(d.create_time,'%Y-%m-%d')='"+date+"'");
        if(StringUtils.isNotEmpty(listFormDto.getOrder())){
            if(listFormDto.getOrder().equals("asc")) {
                wrapper.orderByAsc("d.create_time");
            }
            if(listFormDto.getOrder().equals("desc")){
                wrapper.orderByDesc("d.create_time");
            }
        }

        //将每条数据中的填报信息进行处理
        List<Map<String, Object>> list = dailyFormMapper.getFormList(page, wrapper);
        List<Map<String,Object>> records = new ArrayList<>();
        if(!list.isEmpty()){
            for (Map<String, Object> m : list) {
                Map<String,Object> map = new HashMap<>();
                map.put("账号名",m.get("username"));
                map.put("姓名",m.get("name"));
                map.put("性别",m.get("gender"));
                map.put("身份类别",m.get("identity_category"));
                map.put("学院",m.get("department"));
                map.put("班级",m.get("classname"));
                map.put("填报时间",m.get("create_time"));

                //填报的数据情况
                map.put("身体状况",m.get("physical_condition"));
                String dateKey = dateBefore+"至"+datePattern;
                String key;
                StringBuffer value = new StringBuffer();
                key= dateKey+"是否到达或途径疫情防控重点地区";
                value.append(m.get("to_epidemic_area"));
                if (StringUtils.isNotEmpty((CharSequence) m.get("area_location"))){
                   value.append(" "+m.get("area_location"));
                }
                if (m.get("area_leave_time")!=null){
                    value.append(" "+MyDateUtil.getDateFromPattern((Date) m.get("area_leave_time")));
                }
                map.put(key,value.toString());
                value.setLength(0);
                key = dateKey + "是否接触过'近14天出入过疫情重点防控地区'的人员";
                value.append(m.get("contact_person"));
                if (m.get("person_last_time")!=null){
                    value.append(" "+MyDateUtil.getDateFromPattern((Date) m.get("person_last_time")));
                }
                map.put(key,value.toString());
                value.setLength(0);
                key = dateKey + "是否有接触过疑似/确诊病例";
                value.append(m.get("contact_suspected_case"));
                if (m.get("case_last_time")!=null){
                    value.append(" "+MyDateUtil.getDateFromPattern((Date) m.get("case_last_time")));
                }
                map.put(key,value.toString());
                value.setLength(0);
                key = "是否在莞隔离医学观察";
                value.append(m.get("is_medical_observation"));
                if (m.get("temination_observation_time")!=null){
                    value.append(" "+MyDateUtil.getDateFromPattern((Date) m.get("temination_observation_time")));
                }
                map.put(key,value.toString());
                value.setLength(0);
                key ="目前是否在莞";
                value.append(m.get("in_guan"));
                if(StringUtils.isNotEmpty((CharSequence) m.get("guanTownStreet"))){
                    value.append(" "+m.get("guanTownStreet"));
                }
                if (StringUtils.isNotEmpty((String)m.get("province_city"))){
                    value.append(" "+m.get("province_city"));
                }
                if (m.get("back_guan_time")!=null){
                    value.append(" "+MyDateUtil.getDateFromPattern((Date) m.get("back_guan_time")));
                }
                if (StringUtils.isNotEmpty((CharSequence) m.get("back_guan_transportation"))){
                    value.append(" "+m.get("back_guan_transportation"));
                }
                if (StringUtils.isNotEmpty((CharSequence) m.get("back_route_time"))){
                    value.append(" "+m.get("back_route_time"));
                }
                map.put(key,value.toString());
                value.setLength(0);
                key =dateKey+"是否有离莞出行的行动";
                value.append(m.get("is_leave_guan"));
                if (StringUtils.isNotEmpty((CharSequence)m.get("leave_time_place"))){
                    value.append(" "+m.get("leave_time_place"));
                }
                map.put(key,value.toString());
                value.setLength(0);
                key ="是否为重点人群";
                value.append(m.get("is_midpoint"));
                map.put(key,value.toString());
                value.setLength(0);
                key ="同住的家庭成员是否有如下情况";
                value.append(m.get("family_condition"));
                map.put(key,value.toString());
                map.put("备注",m.get("remark"));
                map.put("今日体温",m.get("temperature"));
                records.add(map);
            }
        }
        return page.setRecords(records);
    }
}
